package com.ibm.demo_hibernate_2;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.portlet.*;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

import HibernateUtil.HibernateUtil;
import Data.TblMoto;

/**
 * A sample portlet based on GenericPortlet
 */
public class Demo_hibernate_2Portlet extends GenericPortlet {

	public static final String JSP_FOLDER    = "/_demo_hibernate_2/jsp/";    // JSP folder name

	public static final String VIEW_JSP      = "Demo_hibernate_2PortletView";         // JSP file name to be rendered on the view mode
	public static final String SESSION_BEAN  = "Demo_hibernate_2PortletSessionBean";  // Bean name for the portlet session
	public static final String FORM_SUBMIT   = "Demo_hibernate_2PortletFormSubmit";   // Action name for submit form
	public static final String FORM_TEXT     = "Demo_hibernate_2PortletFormText";     // Parameter name for the text input



	 
	/**
	 * @see javax.portlet.Portlet#init()
	 */
	public void init() throws PortletException{
		super.init();
	}

	/**
	 * Serve up the <code>view</code> mode.
	 * 
	 * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
	 */
	public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
		// Set the MIME type for the render response
		response.setContentType(request.getResponseContentType());

		// Check if portlet session exists
		Demo_hibernate_2PortletSessionBean sessionBean = getSessionBean(request);
		if( sessionBean==null ) {
			response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
			return;
		}

		// Invoke the JSP to render
		PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
		rd.include(request,response);
	}

	/**
	 * Process an action request.
	 * 
	 * @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
	 */
	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
		if( request.getParameter(FORM_SUBMIT) != null ) {
			// Set form text in the session bean
			Demo_hibernate_2PortletSessionBean sessionBean = getSessionBean(request);
			BigDecimal id;
			String SoMay = "";
			String SoKhung = "";
			long NuocSanXuat = 0;
			short nam_san_xuat = 0;
			int dung_tich = 0;
			Date nien_han_su_dung = null;
			byte songuoi_duocphepcho = 0;
			//Blob hinh_anh;
			String nguon_goc = "";
			String so_chung_tu = "";
			Date ngaycap_chungtu = null;
			String coquan_capchungtu = "";
			String loai_nhien_lieu = "";
			long cong_xuat = 0;
			String mau_xe = "";
			long nguoi_tao = 0;
			Date ngay_tao = null;
			long nguoi_sua = 0;
			Date ngay_sua = null;
			String trang_thai = "";
			String noi_bao = "";
			Date ngay_bao = null;
			String ghichu = "";
			long nhanhieu_loaixe_id;
			String phien_ban = "";
			String command_add="";
			String command = "";
			String command_del="";

			if( sessionBean != null )
				sessionBean.setFormText(request.getParameter(FORM_TEXT));
			SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			Session session = null;
			Transaction transaction = null;
			TblMoto xe = null;
			command_add = request.getParameter("command_add");
			command = request.getParameter("command");
			command_del = request.getParameter("command_del");
			if(command_add.equals("add")||command.equals("edit")||command_del.equals("delete")){
				if(command_add.equals("add")){
					command = "";
					id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id_add")));
					SoMay =request.getParameter("so_may_add");
					SoKhung = request.getParameter("so_khung_add");
					NuocSanXuat = Integer.parseInt(request.getParameter("nuoc_san_xuat_add"));
					nam_san_xuat = Short.parseShort((request.getParameter("nam_san_xuat_add")));
					dung_tich= Integer.parseInt((request.getParameter("dung_tich_add")));
					nien_han_su_dung= convertStringToDate(request.getParameter("nien_han_su_dung_add"));
					songuoi_duocphepcho= Byte.parseByte((request.getParameter("songuoi_duocphepcho_add")));
					nguon_goc= request.getParameter("nguon_goc_add");
					so_chung_tu = request.getParameter("so_chung_tu_add");
					ngaycap_chungtu= convertStringToDate(request.getParameter("ngaycap_chungtu_add"));
					coquan_capchungtu= request.getParameter("coquan_capchungtu_add");
					loai_nhien_lieu= request.getParameter("loai_nhien_lieu_add");
					cong_xuat= Integer.parseInt((request.getParameter("cong_xuat_add")));
					mau_xe= request.getParameter("mau_xe_add");
					nguoi_tao= Long.parseLong((request.getParameter("nguoi_tao_add")));
					ngay_tao= convertStringToDate(request.getParameter("ngay_tao_add"));
					nguoi_sua= Long.parseLong(request.getParameter("nguoi_sua_add"));
					ngay_sua= convertStringToDate(request.getParameter("ngay_sua_add"));
					trang_thai= request.getParameter("trang_thai_add");
					noi_bao= request.getParameter("noi_bao_add");
					ngay_bao= convertStringToDate(request.getParameter("ngay_bao_add"));
					ghichu= request.getParameter("ghichu_add");
					nhanhieu_loaixe_id= Integer.parseInt((request.getParameter("nhanhieu_loaixe_id_add")));
					phien_ban = request.getParameter("phien_ban_add");	
					xe = new TblMoto();
					xe.setId(id);
					xe.setSoMay(SoMay);
					xe.setSoKhung(SoKhung);
					xe.setNuocSanXuat(NuocSanXuat);
					xe.setNamSanXuat(nam_san_xuat);
					xe.setDungTich(dung_tich);
					xe.setCongXuat(cong_xuat);
					xe.setNienHanSuDung(nien_han_su_dung);
					xe.setSonguoiDuocphepcho(songuoi_duocphepcho);
					xe.setNguonGoc(nguon_goc);
					xe.setSoChungTu(so_chung_tu);
					xe.setNgaycapChungtu(ngaycap_chungtu);
					xe.setCoquanCapchungtu(coquan_capchungtu);
					xe.setLoaiNhienLieu(loai_nhien_lieu);
					xe.setMauXe(mau_xe);
					xe.setNguoiTao(nguoi_tao);
					xe.setNgayTao(ngay_tao);
					xe.setNguoiSua(nguoi_sua);
					xe.setNgaySua(ngay_sua);
					xe.setTrangThai(trang_thai);
					xe.setNoiBao(noi_bao);
					xe.setNgayBao(ngay_bao);
					xe.setGhichu(ghichu);
					xe.setNhanhieuLoaixeId(nhanhieu_loaixe_id);
					xe.setPhienBan(phien_ban);
					try {
						session = sessionFactory.openSession();
						transaction = session.beginTransaction();
						session.save(xe);
						transaction.commit();
					} catch (HibernateException e) {
						// TODO Auto-generated catch block
						try {
							transaction.rollback();
						} catch (HibernateException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						e.printStackTrace();
					}finally{
						try {
							session.flush();
							session.close();
						} catch (HibernateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

					
				}
				if(command.equals("edit")){
					command_add="";
					id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id")));
					SoMay =request.getParameter("so_may");
					SoKhung = request.getParameter("so_khung");
					NuocSanXuat = Integer.parseInt(request.getParameter("nuoc_san_xuat"));
					nam_san_xuat = Short.parseShort((request.getParameter("nam_san_xuat")));
					dung_tich= Integer.parseInt((request.getParameter("dung_tich")));
					nien_han_su_dung= convertStringToDate(request.getParameter("nien_han_su_dung"));
					songuoi_duocphepcho= Byte.parseByte((request.getParameter("songuoi_duocphepcho")));
					//hinh_anh= request.getParameter("id");
					nguon_goc= request.getParameter("nguon_goc");
					so_chung_tu = request.getParameter("so_chung_tu");
					ngaycap_chungtu= convertStringToDate(request.getParameter("ngaycap_chungtu"));
					coquan_capchungtu= request.getParameter("coquan_capchungtu");
					loai_nhien_lieu= request.getParameter("loai_nhien_lieu");
					cong_xuat= Integer.parseInt((request.getParameter("cong_xuat")));
					mau_xe= request.getParameter("mau_xe");
					nguoi_tao= Long.parseLong((request.getParameter("nguoi_tao")));
					ngay_tao= convertStringToDate(request.getParameter("ngay_tao"));
					nguoi_sua= Long.parseLong(request.getParameter("nguoi_sua"));
					ngay_sua= convertStringToDate(request.getParameter("ngay_sua"));
					trang_thai= request.getParameter("trang_thai");
					noi_bao= request.getParameter("noi_bao");
					ngay_bao= convertStringToDate(request.getParameter("ngay_bao"));
					ghichu= request.getParameter("ghichu");
					nhanhieu_loaixe_id= Integer.parseInt((request.getParameter("nhanhieu_loaixe_id")));
					phien_ban = request.getParameter("phien_ban");	
					xe = new TblMoto(); 
					xe.setId(id);
					xe.setSoMay(SoMay);
					xe.setSoKhung(SoKhung);
					xe.setNuocSanXuat(NuocSanXuat);
					xe.setNamSanXuat(nam_san_xuat);
					xe.setDungTich(dung_tich);
					xe.setCongXuat(cong_xuat);
					xe.setNienHanSuDung(nien_han_su_dung);
					xe.setSonguoiDuocphepcho(songuoi_duocphepcho);
					xe.setNguonGoc(nguon_goc);
					xe.setSoChungTu(so_chung_tu);
					xe.setNgaycapChungtu(ngaycap_chungtu);
					xe.setCoquanCapchungtu(coquan_capchungtu);
					xe.setLoaiNhienLieu(loai_nhien_lieu);
					xe.setMauXe(mau_xe);
					xe.setNguoiTao(nguoi_tao);
					xe.setNgayTao(ngay_tao);
					xe.setNguoiSua(nguoi_sua);
					xe.setNgaySua(ngay_sua);
					xe.setTrangThai(trang_thai);
					xe.setNoiBao(noi_bao);
					xe.setNgayBao(ngay_bao);
					xe.setGhichu(ghichu);
					xe.setNhanhieuLoaixeId(nhanhieu_loaixe_id);
					xe.setPhienBan(phien_ban);
					try {
						session = sessionFactory.openSession();
						transaction = session.beginTransaction();
						session.update(xe);
						transaction.commit();
					} catch (HibernateException e) {
						// TODO Auto-generated catch block
						try {
							transaction.rollback();
						} catch (HibernateException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						e.printStackTrace();
					}finally{
						try {
							session.flush();
							session.close();
						} catch (HibernateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}					
				}
				if(command_del.equals("delete")){
					id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id_del")));
					motoDAO objDAO = new motoDAO();
					xe = objDAO.getMotobyID(id);
					try {
						session = sessionFactory.openSession();
						transaction = session.beginTransaction();
						session.delete(xe);
						transaction.commit();
					} catch (HibernateException e) {
						// TODO Auto-generated catch block
						try {
							transaction.rollback();
						} catch (HibernateException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						e.printStackTrace();
					}finally{
						try {
							session.flush();
							session.close();
						} catch (HibernateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}				}
			}
			}
	}

	/**
	 * Get SessionBean.
	 * 
	 * @param request PortletRequest
	 * @return Demo_hibernate_2PortletSessionBean
	 */
	private static Demo_hibernate_2PortletSessionBean getSessionBean(PortletRequest request) {
		PortletSession session = request.getPortletSession();
		if( session == null )
			return null;
		Demo_hibernate_2PortletSessionBean sessionBean = (Demo_hibernate_2PortletSessionBean)session.getAttribute(SESSION_BEAN);
		if( sessionBean == null ) {
			sessionBean = new Demo_hibernate_2PortletSessionBean();
			session.setAttribute(SESSION_BEAN,sessionBean);
		}
		return sessionBean;
	}

	/**
	 * Returns JSP file path.
	 * 
	 * @param request Render request
	 * @param jspFile JSP file name
	 * @return JSP file path
	 */
	private static String getJspFilePath(RenderRequest request, String jspFile) {
		String markup = request.getProperty("wps.markup");
		if( markup == null )
			markup = getMarkup(request.getResponseContentType());
		return JSP_FOLDER + markup + "/" + jspFile + "." + getJspExtension(markup);
	}

	/**
	 * Convert MIME type to markup name.
	 * 
	 * @param contentType MIME type
	 * @return Markup name
	 */
	private static String getMarkup(String contentType) {
		if( "text/vnd.wap.wml".equals(contentType) )
			return "wml";
        else
            return "html";
	}

	/**
	 * Returns the file extension for the JSP file
	 * 
	 * @param markupName Markup name
	 * @return JSP extension
	 */
	private static String getJspExtension(String markupName) {
		return "jsp";
	}
	
	private Date convertStringToDate(String str){
		Date date = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = sdf.parse(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return date;
	}

}
